<script lang="ts" setup>
import { computed, reactive, ref, unref } from 'vue';
import { Button, Checkbox, Col, Form, Input, Row } from 'ant-design-vue';
import LoginFormTitle from './login-form-title.vue';

import { useI18n } from '@pkg/locale';
import { useMessage } from '@/hooks/web/useMessage';
import { useUserStore } from '@/store/user';
import { LoginStateEnum, useFormRules, useFormValid, useLoginState } from './use-login';
import { useDesign } from '@/hooks/web/useDesign';

const ACol = Col;
const ARow = Row;
const FormItem = Form.Item;
const InputPassword = Input.Password;
const { t } = useI18n();
const { notification, createErrorModal } = useMessage();
const { prefixCls } = useDesign('login');
const userStore = useUserStore();

const { setLoginState, getLoginState } = useLoginState();
const { getFormRules } = useFormRules();

const formRef = ref();
const loading = ref(false);
const loadingCode = ref(false);
const rememberMe = ref(false);
const base64CaptchaCode = ref('');

const formData = reactive({
  account: '',
  password: '',
  captchaCodeId: '',
  captchaCode: '',
});

const { validForm } = useFormValid(formRef);
//onKeyStroke('Enter', handleLogin);

const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN);
handleClickCaptcha();

async function handleClickCaptcha() {
  const captchaData: any = await userStore.getCaptchaCode();
  loadingCode.value = true;
  formData.captchaCodeId = captchaData.captchaCodeId;
  base64CaptchaCode.value = captchaData.base64CaptchaCode;
}

async function handleLogin() {
  const data = await validForm();
  if (!data) return;
  try {
    loading.value = true;
    const userInfo: any = await userStore.login({
      password: data.password,
      username: data.account,
      captchaCodeId: data.captchaCodeId,
      captchaCode: data.captchaCode,
      mode: 'none', //不要默认的错误提示
    });
    console.info('userInfo', userInfo);
    if (userInfo) {
      notification.success({
        message: t('sys.login.loginSuccessTitle'),
        description: `${t('sys.login.loginSuccessDesc')}: ${userInfo.nickName}`,
        duration: 3,
      });
    }
  } catch (error) {
    createErrorModal({
      title: t('sys.api.errorTip'),
      content: ((error as unknown) as Error).message || t('sys.api.networkExceptionMsg'),
      getContainer: () => document.body.querySelector(`.${prefixCls}`) || document.body,
    });
  } finally {
    loading.value = false;
  }
}

/*let route = useRoute();
const account: any = route.query.account;
const tempCode: any = route.query.tempCode;
if (account && tempCode) {
  handleThirdLogin(account, tempCode);
}

async function handleThirdLogin(account, tempCode) {
  await userStore.thirdLogin({
    account: account,
    tempCode: tempCode,
    mode: 'none',
  });
}*/
</script>
<template>
  <LoginFormTitle v-show="getShow" class="enter-x" />
  <Form class="p-4 enter-x" :model="formData" :rules="getFormRules" ref="formRef" v-show="getShow" @keypress.enter="handleLogin">
    <FormItem name="account" class="enter-x">
      <Input size="large" v-model:value="formData.account" :placeholder="t('sys.login.userName')" class="fix-auto-fill" />
    </FormItem>
    <FormItem name="password" class="enter-x">
      <InputPassword size="large" visibilityToggle v-model:value="formData.password" :placeholder="t('sys.login.password')" />
    </FormItem>
    <FormItem name="captchaCodeId" v-show="false">
      <Input v-model:value="formData.captchaCodeId" />
    </FormItem>
    <FormItem name="captchaCode" class="enter-x">
      <InputGroup>
        <Input size="large" v-model:value="formData.captchaCode" style="width: calc(100% - 150px); min-width: auto;" placeholder="图形验证码" />
        <a-button style="width: 140px;margin-left: 10px; min-width: auto; padding: 0;display:inline;" size="large"><img :src="base64CaptchaCode" alt="点击刷新" @click="handleClickCaptcha" style="width: 100%; height: 34px"/></a-button>
      </InputGroup>
    </FormItem>
    <ARow class="enter-x">
      <ACol :span="12">
        <FormItem>
          <!-- No logic, you need to deal with it yourself -->
          <Checkbox v-model:checked="rememberMe" size="small">
            {{ t('sys.login.rememberMe') }}
          </Checkbox>
        </FormItem>
      </ACol>
      <!--      <ACol :span="12">
        <FormItem :style="{ 'text-align': 'right' }">
          &lt;!&ndash; No logic, you need to deal with it yourself &ndash;&gt;
          <Button type="link" size="small" @click="setLoginState(LoginStateEnum.RESET_PASSWORD)">
            {{ t('sys.login.forgetPassword') }}
          </Button>
        </FormItem>
      </ACol>-->
    </ARow>

    <FormItem class="enter-x">
      <Button type="primary" size="large" block @click="handleLogin" :loading="loading">
        {{ t('sys.login.loginButton') }}
      </Button>
      <!-- <Button size="large" class="mt-4 enter-x" block @click="handleRegister">
        {{ t('sys.login.registerButton') }}
      </Button> -->
    </FormItem>
    <!--    <ARow class="enter-x">
      <ACol :md="8" :xs="24">
        <Button block @click="setLoginState(LoginStateEnum.MOBILE)">
          {{ t('sys.login.mobileSignInFormTitle') }}
        </Button>
      </ACol>
      <ACol :md="8" :xs="24" class="!my-2 md:!my-0 xs:mx-0 md:mx-2">
        <Button block @click="setLoginState(LoginStateEnum.QR_CODE)">
          {{ t('sys.login.qrSignInFormTitle') }}
        </Button>
      </ACol>
      <ACol :md="7" :xs="24">
        <Button block @click="setLoginState(LoginStateEnum.REGISTER)">
          {{ t('sys.login.registerButton') }}
        </Button>
      </ACol>
    </ARow>

    <Divider class="enter-x">{{ t('sys.login.otherSignIn') }}</Divider>

    <div class="flex justify-evenly enter-x" :class="`${prefixCls}-sign-in-way`">
      <GithubFilled />
      <WechatFilled />
      <AlipayCircleFilled />
      <GoogleCircleFilled />
      <TwitterCircleFilled />
    </div>-->
  </Form>
</template>
